package com.wcfsy.wechat.wx.controller;





import java.util.Date;
import java.util.LinkedList;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.wcfsy.wechat.wx.client.Client;
import com.wcfsy.wechat.wx.entity.WechatUserInfo;
import com.wcfsy.wechat.wx.service.RegisteredService;
import com.wcfsy.wechat.wx.service.WeChatQrCodeService;
import com.wcfsy.wechat.wx.util.DateStyle;
import com.wcfsy.wechat.wx.util.DateUtil;
import com.wcfsy.wechat.wx.util.JsonMessage;
import com.wcfsy.wechat.wx.util.StringUtil;
import com.wcfsy.wechat.wx.util.WechatUtil;
import com.wcfsy.wechat.wx.util.XMLHelper;
import com.wcfsy.wechat.wx.util.ehcache.EHCacheConfig;
import com.wcfsy.wechat.wx.util.ehcache.EHCacheUtil;

/**
 *  微信端登录接口
 * @author rod zhong 
 *
 */
@Controller
@RequestMapping("/api/")
public class LoginApiController extends BaseController{

	private  Logger logger = LoggerFactory.getLogger(this.getClass());
	
	@Resource
	private RegisteredService registeredService;
	
	@Resource
	private WechatUtil wechatUtil;
	
	@Resource
	private WeChatQrCodeService weChatQrCodeService;
	
	/**
	 * 登录接口
	 * @param code
	 * @param iphone
	 * @param password
	 * @param request
	 * @param response
	 * @return
	 */
//	@RequestMapping(value="login",produces={"application/json;charset=UTF-8"})
//	@ResponseBody
//	public String login(@Param("unionid")String unionid,@Param("code")String code,@Param("phone")String phone ,@Param("password")String password,HttpServletRequest request,HttpServletResponse response){
////		response.addHeader("Access-Control-Allow-Origin", "*");
//		JSONObject json = new JSONObject();
//		WechatUserInfo wechatUserInfo = new WechatUserInfo();
//		WechatUserInfo userInfoUpdate = new WechatUserInfo();
//		if(isLogin(phone, request)){
//			return WeChatHttpUtil.resultJson("1002", "登录成功", json);
//		}
//		try{
//			if(StringUtils.isNotEmpty(unionid)){//如果cookie 有就去数据库拿到unionid 自动登录
//				wechatUserInfo.setUnionid(unionid);
//				WechatUserInfo userCookie = registeredService.getWechatUserInfo(wechatUserInfo);
//				if(userCookie == null){
//					if(StringUtils.isNotEmpty(phone)){
//						if(StringUtils.isEmpty(password)){
//							return WeChatHttpUtil.resultJson("-1", "密码不能为空", json);
//						}
//						WechatUserInfo wechatUser= new WechatUserInfo();
//						wechatUser.setMobile(phone);
//						wechatUser = registeredService.getWechatUserInfo(wechatUser);
//						String pwd = MD5.encode(password, "utf-8");
//						if(!pwd.equals(wechatUser.getLoginPwd())){
//							logger.warn("密码错误 ");
//							return WeChatHttpUtil.resultJson("-1", "密码错误", json);
//						}
//						EHCacheUtil.setValue(EHCacheConfig.EHCACHENAME, "session_"+wechatUser.getMobile(), wechatUser, 24*60*60);
//						userInfoUpdate.setUnionid(unionid);
//						userInfoUpdate.setId(wechatUser.getId());
//						registeredService.updateWechatUserInfo(userInfoUpdate);//更新数据库最后登录时间
//						logger.info("登录成功  = " + json);
//						json.put("phone", wechatUser.getMobile());
//						json.put("userId", wechatUser.getId());
//						return WeChatHttpUtil.resultJson("1002", "已登录", json);
//					}else{
//						logger.warn("手机号不能为空 phone is null ");
//						return WeChatHttpUtil.resultJson("-1", "手机号不能为空", json);
//					}
//				}
//				if(StringUtils.isNotEmpty(userCookie.getUnionid())){
//					if(!unionid.equals(userCookie.getUnionid())){
//						logger.warn("unionid 与上一次登录不一致 ");
//						return WeChatHttpUtil.resultJson("-1", "登录设备不一致", json);
//					}
//				}
//				request.getSession().setAttribute("session_"+phone, userCookie);
//				EHCacheUtil.setValue(EHCacheConfig.EHCACHENAME, "session_"+phone, userCookie, 24*60*60);
//				logger.warn("用户通过 unionid 登录的");
//				json.put("phone", userCookie.getMobile());
//				json.put("userId", userCookie.getId());
//				return WeChatHttpUtil.resultJson("0", "登录成功 ", json);
//			}else{
//				if(StringUtils.isNotEmpty(code)){
//					com.wcfsy.wechat.wx.util.WechatUtil.WechatResp resp = wechatUtil.wechatAccessToken(code);
//					logger.info("wechatAccessToken is resp = " + JSON.toJSONString(resp));
//					if(!resp.isSuccess()){
//						logger.warn("获取token失败 : " + resp.toString());
//					}
//					logger.info("WechatResp  = " + resp.toString() +"{"+resp.getString("access_token") +","+resp.getString("openid")+"}");
//					com.wcfsy.wechat.wx.util.WechatUtil.WechatResp wechatResp = null;
//					try {
//						wechatResp = wechatUtil.wechatUserinfo(resp.getString("access_token"), resp.getString("openid"));
//						logger.info("wechatUserinfo is wechatResp = " + JSON.toJSONString(resp));
//					} catch (Exception e) {
//						logger.warn("获取用户信息异常", e);
//					}
//					if(!wechatResp.isSuccess()){
//						logger.warn("获取用户信息失败 : " + resp.toString());
//					}
//					wechatResp.getString("nickname");
//					if(StringUtils.isEmpty(wechatResp.getString("unionid"))){
//						logger.warn("1004 用户未绑定微信公众号 ");
//						//return WeChatHttpUtil.resultJson("1004", "用户未绑定微信公众号  ", json);
//					}
//					unionid = wechatResp.getString("unionid");
//					logger.info(" 查询unionid =  " +unionid);
//					WechatUserInfo user = null;
//					logger.info(" 查询信息 unionid = " + unionid +",phone = " + phone); 
//					if(StringUtils.isNotEmpty(unionid)){
//						wechatUserInfo.setUnionid(unionid);
//						logger.info("查询到的用户数据 user = " +JSON.toJSONString(wechatUserInfo));
//						user = registeredService.getWechatUserInfo(wechatUserInfo);
//						json.put("unionid", unionid);
//						if(user == null){
//							return WeChatHttpUtil.resultJson("1006", "用户不存在",json);
//						}
//						wechatUserInfo.setMobile(user.getMobile());
//						wechatUserInfo.setId(user.getId());
//						registeredService.updateWechatUserInfo(wechatUserInfo);;
//						logger.info("查询到的用户数据 user = " +user);
//					}else{
//						if(StringUtils.isNotEmpty(phone)){
//							wechatUserInfo.setMobile(phone);
//							user = registeredService.getWechatUserInfo(wechatUserInfo);
//						}
//					}
//					logger.info("user = " + user);
//					if(user == null){
//						logger.info("用户未注册 ");
//						String msg = "";
//						if(StringUtils.isEmpty(unionid)){
//							msg = WeChatHttpUtil.resultJson("-1", "获取unionid失败 ", json);
//							logger.info("获取unionid失败  = "+msg);
//							return msg;
//						}
//						json.put("unionid", unionid);
//						msg = WeChatHttpUtil.resultJson("1006", "未注册  ", json);
//						logger.info("用户未注册   = "+msg);
//						return msg;
//					}else{
//						if(StringUtils.isNotEmpty(unionid)){
//							json.put("unionid", unionid);
//						}
//						if(StringUtils.isNotEmpty(phone)){
//							if(StringUtils.isEmpty(password)){
//								return WeChatHttpUtil.resultJson("-1", "密码不能为空", json);
//							}
//							String pwd = MD5.encode(password, "utf-8");
//							if(!pwd.equals(user.getLoginPwd())){
//								logger.warn("密码错误 ");
//								return WeChatHttpUtil.resultJson("-1", "密码错误", json);
//							}
//						}
//						EHCacheUtil.setValue(EHCacheConfig.EHCACHENAME, "session_"+user.getMobile(), user, 24*60*60);
//						userInfoUpdate.setUnionid(unionid);
//						userInfoUpdate.setId(user.getId());
//						registeredService.updateWechatUserInfo(userInfoUpdate);//更新数据库最后登录时间
//						logger.info("登录成功  = " + json);
//						json.put("phone", user.getMobile());
//						json.put("userId", user.getId());
//						return WeChatHttpUtil.resultJson("1002", "已登录", json);
//					}
//				}else{
//					WechatUserInfo user = null;
//					if(StringUtils.isNotEmpty(phone)){
//						if(StringUtils.isEmpty(password)){
//							logger.warn("密码不能为空 password is null ");
//							return WeChatHttpUtil.resultJson("-1", "密码不能为空", json);
//						}
//						wechatUserInfo.setMobile(phone);
//						user = registeredService.getWechatUserInfo(wechatUserInfo);
//						String pwd = MD5.encode(password, "utf-8");
//						if(!pwd.equals(user.getLoginPwd())){
//							logger.warn("密码错误 ");
//							return WeChatHttpUtil.resultJson("-1", "密码错误", json);
//						}
//					}else{
//						logger.warn("手机号不能为空 phone is null ");
//						return WeChatHttpUtil.resultJson("-1", "手机号不能为空", json);
//					}
//					EHCacheUtil.setValue(EHCacheConfig.EHCACHENAME, "session_"+user.getMobile(), user, 24*60*60);
//					userInfoUpdate.setId(user.getId());
//					registeredService.updateWechatUserInfo(userInfoUpdate);//更新数据库最后登录时间
//					logger.info("登录成功  = " + json);
//					json.put("phone", user.getMobile());
//					json.put("unionid", unionid);
//					json.put("userId", user.getId());
//					return WeChatHttpUtil.resultJson("1002", "已登录", json);
//				}
//			}
//		}catch(Exception e){
//			logger.warn("登录异常" , e);
//			return WeChatHttpUtil.resultJson("-1", "登录异常 ", json);
//		}
//	}
	
	@RequestMapping(value="login",produces={"application/json;charset=UTF-8"})
	@ResponseBody
	public JsonMessage login(@RequestParam(value="unionid",required=false)String unionid,
			@RequestParam(value="code",required=false)String code,@RequestParam(value="mobile",required=false)String mobile,
			@RequestParam(value="name",required=false)String name,@RequestParam(value="password",required=false)String password,
			@RequestParam(value="uid",required=false,defaultValue="0")int uid,HttpServletRequest request){
		try {
			//根据unionId 进行自动登录
			if(StringUtil.isNotEmpty(unionid)){
				WechatUserInfo unionidUser  = new WechatUserInfo();
				unionidUser.setUnionid(unionid);
				WechatUserInfo user = registeredService.getWechatUserInfo(unionidUser);
				if(user!=null){
					if(user.getUid() > 0){
						unionidUser =  (WechatUserInfo)EHCacheUtil.get("session_"+user.getUid());
						unionidUser.setNickname(StringUtil.decode(unionidUser.getNickname()));
						return JsonMessage.getSuccessJson(unionidUser);
					}
				}
			}
			if(uid > 0){
				if(isLogin(uid, request)){
					WechatUserInfo user = (WechatUserInfo)EHCacheUtil.get("session_"+uid);
					user.setNickname(StringUtil.decode(user.getNickname()));
					return JsonMessage.getSuccessJson(user);
				}
			}
			
			if(StringUtils.isNotEmpty(name) && StringUtils.isNotEmpty(password)){
				if(StringUtils.isEmpty(mobile)){
					return JsonMessage.getErrorJson("手机号不能为空");
				}
				logger.info("登录用户信息 name = {0} , password = {1} ,mobile = " + mobile,name , password);
				
				Client e = new Client();
				String result = e.uc_user_login(name, password);
				LinkedList<String> rs = XMLHelper.uc_unserialize(result);
				if(rs.size()>0 && Integer.parseInt(rs.get(0)) > 0){
					int $uid = Integer.parseInt(rs.get(0));
					String $username = rs.get(1);
					String $password = rs.get(2);
					String $email = rs.get(3);
					if($uid > 0) {
						WechatUserInfo user = new WechatUserInfo();
						user.setUid($uid);
						WechatUserInfo loginUser = registeredService.getWechatUserInfo(user);
						if(loginUser == null){
							user.setUserAs($username);
							user.setLoginPwd($password);
							user.setEmail($email);
							user.setUid($uid);
							user.setMobile(mobile);
							if(StringUtils.isNotEmpty(code)){
								com.wcfsy.wechat.wx.util.WechatUtil.WechatResp resp = wechatUtil.wechatAccessToken(code);
								logger.info("wechatAccessToken is resp = " + JSON.toJSONString(resp));
								if(!resp.isSuccess()){
									logger.warn("获取token失败 : " + resp.toString());
								}
								logger.info("WechatResp  = " + resp.toString() +"{"+resp.getString("access_token") +","+resp.getString("openid")+"}");
								com.wcfsy.wechat.wx.util.WechatUtil.WechatResp wechatResp = null;
								try {
									wechatResp = wechatUtil.wechatUserinfo(resp.getString("access_token"), resp.getString("openid"));
									logger.info("wechatUserinfo is wechatResp = " + JSON.toJSONString(resp));
								} catch (Exception e1) {
									logger.warn("获取用户信息异常", e1);
								}
								if(wechatResp.isSuccess()){
									user.setCreateDate(DateUtil.DateToString(new Date(), DateStyle.YYYY_MM_DD_HH_MM_SS));
									user.setUnionid(wechatResp.getString("unionid"));
									user.setHeadimgurl(wechatResp.getString("headimgurl"));
									user.setOpenid(wechatResp.getString("openid"));
									user.setSex(wechatResp.getString("sex"));
									user.setNickname(StringUtil.encode(wechatResp.getString("nickname")));
								}
							}
							JsonMessage qrMsg = weChatQrCodeService.createQrCode("wcfsy"+$uid);
							logger.info("生成二维码 qrMsg = " + JSON.toJSONString(qrMsg));
							if("succeed".equals(qrMsg.getSuccess())){
								user.setQrCode(qrMsg.getMessage());
							}
							user.setStatus("1");
							user.setUserType("1");
							user.setCreateDate(DateUtil.DateToString(new Date(), DateStyle.YYYY_MM_DD_HH_MM_SS));
							registeredService.saveWechatUserInfo(user);
							loginUser = registeredService.getWechatUserInfo(user);
							if(StringUtil.isNotEmpty(loginUser.getNickname())){
								loginUser.setNickname(StringUtil.decode(loginUser.getNickname()));
							}
							EHCacheUtil.setValue(EHCacheConfig.EHCACHENAME, "session_"+loginUser.getUid(), loginUser, 30*24*60*60);
							return JsonMessage.getSuccessJson(loginUser);
						}else{
							if(StringUtils.isNotEmpty($email)){
								user.setEmail($email);
								user.setId(loginUser.getId());
							}
							if(StringUtils.isEmpty(loginUser.getQrCode())){
								JsonMessage qrMsg = weChatQrCodeService.createQrCode("wcfsy"+$uid);
								logger.info("生成二维码 qrMsg = " + JSON.toJSONString(qrMsg));
								if("succeed".equals(qrMsg.getSuccess())){
									user.setQrCode(qrMsg.getMessage());
									loginUser.setQrCode(qrMsg.getMessage());
								}
							}
							user.setMobile(mobile);
							registeredService.updateWechatUserInfo(user);
							loginUser = registeredService.getWechatUserInfo(user);
							if(StringUtil.isNotEmpty(loginUser.getNickname())){
								loginUser.setNickname(StringUtil.decode(loginUser.getNickname()));
							}
							EHCacheUtil.setValue(EHCacheConfig.EHCACHENAME, "session_"+loginUser.getUid(), loginUser, 30*24*60*60);
							return JsonMessage.getSuccessJson(loginUser);
						}
	//				String $ucsynlogin = e.uc_user_synlogin($uid);
	//				System.out.println("登录成功"+$ucsynlogin);
					} else if($uid == -1) {
						return JsonMessage.getErrorJson("用户不存在,或者被删除");
					} else if($uid == -2) {
						return JsonMessage.getErrorJson("密码错误");
					} else {
						return JsonMessage.getErrorJson("未定义");
					}
				}else{
					logger.info("Login failed result"  + result);
					return JsonMessage.getErrorJson("Login failed");
				}
			}else{
				if(StringUtils.isNotEmpty(code)){
					logger.info("登录的code = {0}",code);
					WechatUserInfo user = new WechatUserInfo();
					com.wcfsy.wechat.wx.util.WechatUtil.WechatResp resp = wechatUtil.wechatAccessToken(code);
					logger.info("wechatAccessToken is resp = " + JSON.toJSONString(resp));
					if(!resp.isSuccess()){
						logger.error("获取token失败 : " + resp.toString());
					}
					logger.info("WechatResp  = " + resp.toString() +"{"+resp.getString("access_token") +","+resp.getString("openid")+"}");
					com.wcfsy.wechat.wx.util.WechatUtil.WechatResp wechatResp = null;
					try {
						wechatResp = wechatUtil.wechatUserinfo(resp.getString("access_token"), resp.getString("openid"));
						logger.info("wechatUserinfo is wechatResp = " + JSON.toJSONString(resp));
					} catch (Exception e) {
						logger.error("获取用户信息异常", e);
					}
					WechatUserInfo userCode = new WechatUserInfo();
					WechatUserInfo loginUser  = null ;
					if(wechatResp.isSuccess()){
						user.setCreateDate(DateUtil.DateToString(new Date(), DateStyle.YYYY_MM_DD_HH_MM_SS));
						user.setUnionid(wechatResp.getString("unionid"));
						user.setHeadimgurl(wechatResp.getString("headimgurl"));
						user.setOpenid(wechatResp.getString("openid"));
						user.setSex(wechatResp.getString("sex"));
						user.setNickname(StringUtil.encode(wechatResp.getString("nickname")));
						user.setUnionid(wechatResp.getString("unionid"));
						userCode.setUnionid(wechatResp.getString("unionid"));
						loginUser = registeredService.getWechatUserInfo(userCode);
					}
					user.setMobile(mobile);
					if(loginUser != null && StringUtils.isNotEmpty(loginUser.getEmail())){
						if(loginUser.getUid() < 0){ //返回微信消息给前端
							return JsonMessage.getErrorJson(user);
						}
						user.setId(loginUser.getId());
						registeredService.updateWechatUserInfo(user);
						EHCacheUtil.setValue(EHCacheConfig.EHCACHENAME, "session_"+user.getUid(), user, 30*24*60*60);
						return JsonMessage.getSuccessJson(loginUser);
					}else{
						if(user != null){//返回微信消息给前端
							registeredService.saveWechatUserInfo(user);
							user.setNickname(StringUtil.decode(user.getNickname()));
							return JsonMessage.getErrorJson(user);
						}
					}
				}
				return JsonMessage.getErrorJson("非法请求");
			}
		} catch (Exception e) {
			logger.error("登录异常 " , e);
			return JsonMessage.getErrorJson("网络异常");
		}
	}
	
	/**
	 * 退出登录
	 */
	@RequestMapping(value="loginOut",produces={"application/json;charset=UTF-8"})
	@ResponseBody
	public JsonMessage logout(int uid,HttpServletRequest request){
		Client uc = new Client();
		try{
			if(uid > 0){
				if(isLogin(uid, request)){
					uc.uc_user_synlogout();
					EHCacheUtil.remove("session_" + uid);
					return JsonMessage.getSuccessJson("退出成功");
				}
			}
			return JsonMessage.getSuccessJson("退出成功");
		}catch(Exception e){
			logger.error("退出登录失败",e);
			EHCacheUtil.remove("session_" + uid);
			return JsonMessage.getSuccessJson("退出成功");
		}
	}
	
	/**
	 * 退出登录
	 * @param phone
	 * @param userId
	 * @param request
	 * @return
	 */
//	@RequestMapping(value="loginOut",produces={"application/json;charset=UTF-8"})
//	@ResponseBody
//	public String logOut(String phoneNumber,int userId,HttpServletRequest request){
//		try{
//			if(StringUtils.isEmpty(phoneNumber) || userId == 0){
//				return StringUtil.resultMessage(1002, "您未登录");
//			}
//			logger.info("phoneNumber={0},userId={1}",phoneNumber,userId);
//			WechatUserInfo wechatUserInfo = new WechatUserInfo();
//			wechatUserInfo.setMobile(phoneNumber);
//			wechatUserInfo.setId(userId);
//			wechatUserInfo = registeredService.getWechatUserInfo(wechatUserInfo);
//			EHCacheUtil.remove("session_" + phoneNumber);
//			return StringUtil.resultMessage(0, "成功退出！");
//		}catch(Exception e){
//			logger.warn("退出登录失败",e);
//			return StringUtil.resultMessage(1002, "登录已经过期");
//		}
//	}
}
